﻿using Infra.CustomException.Resources;
using System;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;

namespace Infra.CustomException
{
    public class DalException : BaseException, IExceptionForShow
    {
        public DalException(Exception exception)
            : base(exception)
        {
            if (exception is SqlException && Logger != null)
            {
                var ex = base.InnerException as SqlException;
                var errorMessage = new StringBuilder();
                
                errorMessage.Append("******************************************************************* Data Access Layer Error ***********************************************************");
                foreach (SqlError item in ex.Errors)
                {
                    var counter = 0;
                    errorMessage.AppendFormat("Index #{0}\n Message:{1}\n LineNumber:{2}\n Source: {3}\n Procedure:{4}\n", 
                                                counter++, item.Message, item.LineNumber, item.Source, item.Procedure);
                }
                errorMessage.Append("******************************************************************* Data Access Layer Error ***********************************************************");

                Logger.Error("SQL Exception", ex);
                Logger.Error(errorMessage.ToString());
            }
        }

        public DalException(string message)
            : base(message)
        { }

        public string MessageKey
        {
            get
            {
                return base._message;
            }
        }

        public string GetMessage(CultureInfo culture)
        {
            var result = "";

            if (base._message == null || base._message.Equals(""))
                result = base.GetMessage(base.InnerException, culture);
            else
                result = DalResource.ResourceManager.GetString(base._message, culture);
            
            return result;
        }
    }
}
